package com.preskool.controller;

import com.preskool.dto.ActionResult;
import com.preskool.dto.SubjectVo;
import com.preskool.po.Class;
import com.preskool.po.Subjects;
import com.preskool.service.ClassService;
import com.preskool.service.SubjectsService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Author kennyzzz
 * @Data 2021/1/11 5:08
 */
@RestController
@Slf4j
@Api(value = "Subject接口文档")
public class SubjectsController {
    @Autowired
    private SubjectsService subjectsService;
    @Autowired(required = false)
    private ClassService classService;
    @PostMapping("/showSubjects")
    public ActionResult showSubjectListByPage(Integer currentPage,Integer pageSize,String sortName){
        List<SubjectVo> subjects = subjectsService.findSubjectsByPage(currentPage,pageSize,sortName);
        return new ActionResult(200,"查询成功",subjects);
    }
        @PutMapping("/addSubject")
    public ActionResult addSubject(@RequestBody SubjectVo subjectVo){
        try{
            Subjects subjects = new Subjects();
            Class clazz = classService.findClassByName(subjectVo.getClName());
            subjects.setClid(clazz.getClid());
            subjects.setSubid(subjectVo.getSubid());
            subjects.setSubjectName(subjectVo.getSubjectName());
            int count = subjectsService.addSubject(subjects);
            if(count>0){
                return  new ActionResult(200,"添加成功",null);
            }
        }catch (Exception e){
            return  new ActionResult(204,"该班级不存在",null);
        }
       return  new ActionResult(204,"添加失败,请重新输入",null);

    }
    @DeleteMapping("/deleteSubject")
    public ActionResult deleteTeacher(Integer subid){
        try{
            int count = subjectsService.deleteSubjectBySubid(subid);
            if(count>0){
                return  new ActionResult(200,"delete success",null);
            }
        }catch (Exception e){
            return new ActionResult(204,"the teacher has a class",null);

        }
        return  new ActionResult(201,"no data",null);
    }
    @PostMapping("/updateSubject")
    public ActionResult updateSubject(@RequestBody SubjectVo subjectVo){
        try{
            Subjects subjects = new Subjects();
            Class clazz = classService.findClassByName(subjectVo.getClName());
            subjects.setClid(clazz.getClid());
            subjects.setSubid(subjectVo.getSubid());
            subjects.setSubjectName(subjectVo.getSubjectName());
            int count = subjectsService.updateSubject(subjects);
            if(count>0){
                return  new ActionResult(200,"修改成功",null);
            }
        }catch (Exception e){
            return  new ActionResult(204,"修改失败",null);
        }
        return  new ActionResult(204,"修改失败",null);

    }
}
